#encoding=utf8

import sys
sys.path.append('../')
from db_controlter import DB_controlter
from create_corpus import MyGensim
import time

class LDATopicsDB(DB_controlter):
    def __init__(self):
        DB_controlter.__init__(self)
        
    def insert(self, topic_no, words):
        try:
            self.cursor.execute("""INSERT INTO WebPage_lda_topics(topic_no, words) VALUES('%d', '%s')""" %(topic_no, words))
            self.db.commit()
        except:
            self.db.rollback()

class ShowMyLDA():
    def __init__(self):
        self.mygensim = MyGensim()
        self.lda_model = self.mygensim.get_ldamodel()

    def get_lda_topics_num(self):
        return self.lda_model.num_topics

    def print_lda_topics(self, topn=20):
        return self.lda_model.print_topics(self.get_lda_topics_num(), num_words=topn)

    def print_to_file(self, path='./print_model.lda'):
        f = open(path, "w")
        lda_str = self.print_lda_topics()
        topic_no = 0
        for i in lda_str:
            f.write("Topic #%d: " %topic_no + i.encode("utf-8") + '\n')
            topic_no += 1
        f.close()
        
    def print_to_database(self):
        lda_topics_DB = LDATopicsDB()
        topic_no = 0
        for i in self.print_lda_topics():
            lda_topics_DB.insert(topic_no, "Topic #%d: " %topic_no + i.encode("utf-8") + '\n')
            topic_no += 1

if __name__ == "__main__":

    showmylda = ShowMyLDA()
    
    #将lda模型以可以阅读的方式打印到屏幕
    showmylda.print_lda_topics()
    
    #将lda模型以可以阅读的方式输出到文件
    #showmylda.print_to_file()
    
    #将lda模型以可以阅读的方式保存至数据库
    #showmylda.print_to_database()
